package base.thread.waitNotify;

public class NotifyAndWaitDemo {

    private int i=0;

    private Object obj=new Object();

    //奇数进行打印
    private void odd() throws InterruptedException {

        while (i<10){

            synchronized (obj){
                if (i%2==1){
                    System.out.println("奇数  "+i);
                    i++;
                    obj.notify();
                }else {
                    obj.wait();
                }
            }
        }

    }


    /**
     * 偶数进行打印
     */
     private void even() throws InterruptedException {
        synchronized (obj){
            while (i<10){
                if (i%2==0){
                    System.out.println("偶数  "+i);
                    i++;
                    obj.notify();//唤醒，
                }else {
                    // todo 注意：在使用时需要在synchronized之内，否则抛出IllegalMonitorStateException
                    obj.wait();//等待，在等待时刻将放弃执行权。
                }
            }
        }
    }


    public static void main(String[] args) {
        NotifyAndWaitDemo demo=new NotifyAndWaitDemo();


        Thread thread1=new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    demo.odd();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

         Thread thread2=new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    demo.even();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        thread1.start();
        thread2.start();
    }



}
